<?php
/**
 * Created by PhpStorm.
 * User: wx:wenyi2048
 * Date: 2022/3/19 0019
 * Time: 16:45
 */

namespace app\common\service;



use app\common\model\mk\Orders;
use think\Db;
use think\Exception;

class OrdersService extends Service
{
    protected $tableName = 'sms_mk_orders';

    protected $userAdminId;//店铺管理员id

    protected $store = [];


    public function datalist()
    {
        //添加状态查询
        $this->setDb('orders_view');
        $this->db->where('sms_users_id','=',$this->param['sms_users_id']);
        //20230716改
        if(@$this->param['state'])$this->db->where('state','=',$this->param['state']);
//        $state = [$this->param['state']];
//        if($this->param['state'] == 'paid')
//            $state[] = 'received';
//        if(@$this->param['state'])$this->db->whereIn('state',$state);
        //20230716改
        if(@$this->param['id'])$this->db->where('id','=',$this->param['id']);
        if(!empty($this->param['is_invoice'])){
            $this->db->whereIn('state',['comment','finished']);
        }
        $this->db->where('state','<>','deleted');
        $result = parent::datalist(); // TODO: Change the autogenerated stub
        foreach (@$result['data'] as $v=>$value){
            $oiService = new OrderItemsService();
            $result['data'][$v]['goods'] = $oiService->getGoods($value['id']);
            if($result['data'][$v]['require_photos'])
                $result['data'][$v]['require_photos'] = json_decode($value['require_photos'],true);
        }
        return $result;
    }

    public function getStateSum(){
        $this->setDb('orders_view');
        if(@$this->param['state'])$this->db->where('state','=',$this->param['state']);
        $this->db->where('state','<>','deleted')
            ->where('sms_users_id','=',$this->param['sms_users_id'])
            ->group('state')->field('state,count(state) as sum');
        return $this->db->select();
    }


    /**
     * 获取某订单和订单商品
     */
    public function getOrderGoods($orderId){
        $result = $this->db->where('id','=',$orderId)->find();
        $oiService = new OrderItemsService();
        $result['goods'] = $oiService->getGoods($orderId);
        return $result;
    }

    /**
     * 获取某订单和订单商品 主要用于前端
     */
    public function getUserOrder(){
        if(!$this->param['order_id']) return 0;
        $this->setDb('orders_view');
        $result = $this->db->where('id','=',$this->param['order_id'])
            ->where('sms_users_id','=',$this->param['sms_users_id'])
            ->find();
        if(!$result) return 0;
        $oiService = new OrderItemsService();
        $result['goods'] = $oiService->getGoods($this->param['order_id']);
        return  $result;
    }

    public function dbQuery($params){
        $this->db->alias('o')
            ->join('sms_mk_address a','o.sms_address_id = a.id','left')
            //->where('o.state','<>','require')
            ->order('o.id','desc')
            ->field("o.*,concat_ws('/',a.province,a.city,a.area,a.detailed_address) as address,a.name as username,a.phone");

        if(@$params['number']) $this->db->where('number','like','%'.$params['number'].'%');

        $storeId = $this->checkStoreSelect(@$params['store_id']);
        if($storeId) $this->db->where('o.store_id','=',$storeId);
    }
    /**
     * @param $view
     * @param $params
     * @param int $isdelete  返回全部订单分页
     */
    public function searchPage(&$view,$params,$isdelete = 0){

        $this->dbQuery($params);
        $this->db->where('o.state','<>','require');
        $this->db->where('o.state','<>','deleted');

        $this->pageList($view,$params);
    }

    public function requirePage(&$view,$params,$isdelete = 0){
        $sms_stores_id = getAdminStoreId(@$params['store_id']);
        $this->db->where('is_require','=',1);
        if($sms_stores_id)
            $this->db->where('store_id','=',$sms_stores_id);
        $this->pageList($view,$params);
    }

    /**
     * @param $param
     * @return \think\Response|\think\response\Json|\think\response\Jsonp|\think\response\Redirect|\think\response\View|\think\response\Xml
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 需求阶段店家添加商品
     */
    public function requireGoods($param){
        $orderId = $param['id'];
        $goods = @$param['goods'];
        //添加商品
        if($goods){
            $item = new OrderItemsService($param);
            $total_fee = $item->itemAdd($orderId,$goods);
        }
        //改状态
        $order = Orders::find($orderId);
        if($order['state'] != 'require'){
            return ajax_return_adv_error("状态不对");
        }
        $order->state = 'await';
        $order->total_fee = @$total_fee[1];
        $order->unit_sum = @$total_fee[0];
        $order->require_time = time();
        if(@$param['final_price'] && (int)$param['final_price']) $order->total_fee = $param['final_price'];
        $order->save();
        return ajax_return_adv("编辑成功");
    }

    /**
     * 添加订单 间接添加
     * 直接从规格选择页面添加到一个订单，类似于添加到购物车
     */
    public function createAdd($defAddress){
        //是否已经创建，创建修改
        $order = Db::table($this->tableName)
            ->where('sms_users_id','=',$this->param['sms_users_id'])
            ->where('state','=','await')
            ->where('store_id','=',$this->param['store_id'])
            ->where('is_cart','=',1)
            ->find();
        $goods = $this->param['goods'];
        $result['id'] = $order['id'];
        if($order){
            Db::startTrans();
            try {
                //添加商品
                $item = new OrderItemsService($this->param);
                $total = $item->itemAddUpdate($order['id'],$goods,$order['unit_sum'],$order['total_fee']);

                //重新创建对象，否则报Attempt to assign property 'unit_sum' of non-object",
                $order = Db::table($this->tableName)
                    ->where('sms_users_id','=',$this->param['sms_users_id'])
                    ->where('state','=','await')
                    ->where('is_cart','=',1);
                $order->update(['unit_sum'=>$total[0],'total_fee'=>$total[1]]);
//                $order->unit_sum = $total[0];
//                $order->total_fee = $total[1];
//                $order->save();
                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                throw new Exception('交易失败:'.$e->getMessage());
            }
        }else{//否则从新添加
            return $this->create(null,1,$defAddress);
        }
        return $result;
    }

    /**
     * @param $orderId 删除订单
     */
    public function createDel($order){
//        $order =  Orders::where('sms_users_id','=',$this->param['sms_users_id'])
//            ->where('state','=','await')
//            ->find($orderId);
//        if($order){
//            Db::startTrans();
//            try {
                $order->state = 'deleted';
                //$order->number = $dno;
                //$order->sms_users_id = $this->param['sms_users_id'];
                //$order->comment = @$this->param['comment'];
                //$order->sms_address_id = @$this->param['sms_address_id'];
                //$order->create_time = time();
                //$order->store_id = @$this->param['store_id'];
                //$order->is_require = 0;
                $order->unit_sum = 0;
                $order->total_fee = 0;
                $order->save();

                Db::table('sms_mk_order_items')->where('sms_orders_id','=',$order->id)->delete();

//                Db::commit();
//            }catch (Exception $e){
//                Db::rollback();
//                throw new Exception('交易失败:'.$e->getMessage());
//            }

//        }
    }


    /**
     *确定订单，带id   间接模块
     *主要是从待付款进去的
     */
    public function createUpdate($orderId,$defAddress=''){
        //先查状态，如果是await和是间接添加模块，则走此模块，否则状态不对
        $order = Db::table($this->tableName)->find($orderId);
        if($order['state'] != 'await'){
            throw new Exception('订单状态不对');
        }
//        if($order['is_require'] == 1){//需求路径  直接返回
//            return $this->requireOrder($orderId);
//        }
//        if($order['is_cart'] != 1){//不走需求就间接
//            throw new Exception('订单状态不对');
//        }
        //先删除
        //$this->createDel($orderId);
        //再修改
        return $this->create($orderId,1,$defAddress);
    }

    /**
     * 创建订单，不带id   直接模块
     */
    public function create($orderId = null,$isCart = 0,$defAddress=''){
        $validate = new \app\common\validate\mk\Orders();
        if(!$isCart)
            if (!$validate->check($this->param)) {
                throw new Exception($validate->getError());
            }
        $goods = $this->param['goods'];
        $dno=createOrderNumber($this->param['sms_users_id'].@$this->param['sms_address_id'].$this->param['store_id'],'D');//订单编号;
        //$this->param['sms_address_id'];//没有地址，还要去获取用户默认地址
        if(@$this->param['sms_address_id']) $defAddress = $this->param['sms_address_id'];

        Db::startTrans();
        try {
            if($orderId){
                $order = Orders::find($orderId);
                $this->createDel($order);
            }
            else $order = new Orders();
//            $order->state = 'deleted';
            $order->number = $dno;
            $order->sms_users_id = $this->param['sms_users_id'];
            $order->comment = @$this->param['comment'];
            $order->sms_address_id = $defAddress;//@$this->param['sms_address_id'];
            $order->create_time = time();
            $order->store_id = $this->param['store_id'];
            $order->is_require = 0;
            $order->is_cart = $isCart;
            $order->save();

            //添加商品
            $item = new OrderItemsService($this->param);
            $total = $item->itemAdd($order->id,$goods);
            $order->unit_sum = $total[0];
            $order->total_fee = $total[1];
            $order->state = 'await';
            $order->save();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            throw new Exception('交易失败:'.$e->getMessage());
        }
        return  $order;
        //return apiSuccess($order);
    }
    /**
     * 创建需求
     */
    public function requireAdd(){
        $dno=createOrderNumber($this->param['sms_users_id'],'D');//订单编号;
        $photos = $this->param['require_photos'];
        if(!is_array($photos)) $photos = [$photos];
        $photos = json_encode($photos);
        $data = [
            'state'=>'require',
            'number'=>$dno,
            'sms_users_id'=> $this->param['sms_users_id'],
            'comment'=>@$this->param['comment'],
            'require_text'=>$this->param['require_text'],
            'require_photos'=>$photos,
            'create_time'=>time(),
            'is_require'=>1,
            'store_id'=>@$this->param['store_id']
        ];

        //添加商品
        return $this->db->insertGetId($data);
    }

    /**
     * 需求确认付款只修改地址，其他不变
     */
    public function requireOrder($orderId){
        //$order->sms_address_id = @$this->param['sms_address_id'];
        if(!@$this->param['sms_address_id']) throw  new  Exception('收获地址不能为空');
        $order = Orders::find($orderId);
        $order->sms_address_id = @$this->param['sms_address_id'];
        return $order;
    }


    public function editState($id,$beforeState,$newState,$checkSelf = false,$upField = array()){
        if(!$id) throw new Exception('订单丢失');
        $order = Orders::find($id);
        if($checkSelf){
            //验证是否是自己的订单
            if(@$this->param['sms_users_id'] != $order['sms_users_id'])
                throw new Exception('不是自己的订单');
        }
        if(!is_array($beforeState)) $beforeState = array($beforeState);
        if(in_array($order['state'],$beforeState)){
            foreach ($upField as $field=>$value){
                $order[$field] = $value;
            }
            $order->state = $newState;
            return $order->save();
        }
        throw new Exception('订单状态不对');
    }

    public function editAddress($id,$beforeState){
        if(!$id) throw new Exception('订单丢失');
        if(!@$this->param['address_id']) throw new Exception('需指定收货地址');
        $order = Orders::find($id);
        if($order['sms_users_id'] != @$this->param['sms_users_id']){
            //验证是否是自己的订单
            throw new Exception('不是自己的订单');
        }
        if($order->state != $beforeState){
            throw new Exception('订单状态不对');
        }
        $order->sms_address_id = $this->param['address_id'];
        return $order->save();

    }



    /**
     * 用户支付成功的回调
     */
    static function userPay12($order_number,$pay_number,$total_fee){

        $order = Db::table('sms_mk_orders')
            ->where('number','=',$order_number)
            ->find();
        if(empty($order)){
            return false;
        }
        $data = [
            'paid_time'=>time(),
            'pay_number'=>$pay_number,
            'state'=>'paid'
            //'total_fee'=>$total_fee/100
        ];

        $where = ['id'=>$order['id'],'state'=>'await'];

        $orderUpdate = Db::table('sms_mk_orders')
            ->where($where)
            ->update($data);

        //分账
        $wxOrderNo = $order['pay_number'];       //微信订单号（商户订单号与微信订单号二选一，至少填一个）
        $totalFee =$order['total_fee'];          //订单金额
        $Wxrefund = new WxpayService();
        $storeId = $order['store_id'];//店铺id
        $result  = $Wxrefund->spoilsSingle($order_number,$wxOrderNo,$storeId,$totalFee);

        if(!empty($orderUpdate) && $orderUpdate){
            return true;
        }else{
            return false;
        }

    }

    static function userPay($order_number,$pay_number,$total_fee){

        $order = Db::table('sms_mk_orders')
            ->where('number','=',$order_number)
            ->find();
        if(empty($order)){
            return false;
        }
        $data = [
            'paid_time'=>time(),
            'pay_number'=>$pay_number,
            'state'=>'paid'
            //'total_fee'=>$total_fee/100
        ];

        $where = ['id'=>$order['id'],'state'=>'await'];

        $orderUpdate = Db::table('sms_mk_orders')
            ->where($where)
            ->update($data);

        if(!empty($orderUpdate) && $orderUpdate){
            return true;
        }else{
            return false;
        }

    }
}